import roles from '../../api/roles'

import {
  SHOW_SUCCESS_MSG,
  SHOW_ERROR_MSG,
  SET_ROLES,
  INSERT_ROLE,
  UPDATE_ROLE,
  DELETE_ROLE
} from '../mutation-types'

// initial state
const state = {
  roles: []
}

// getters
const getters = {
  getRoles: state => state.roles
}

// actions
const actions = {
  //请求系统角色列表
  reqGetRoles({
    commit,
    state
  }, payload) {
    commit(SET_ROLES, {
      roles: []
    })
    roles.getRoles(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SET_ROLES, {
            roles: result.results.roles
          })
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求插入系统角色
  reqInsertRole({
    commit,
    state
  }, payload) {
    // debugger;
    roles.insertRole(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存系统角色信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求更新系统角色
  reqUpdateRole({
    commit,
    state
  }, payload) {
    roles.updateRole(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存系统角色信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求删除系统角色
  reqDeleteRole({
    commit,
    state
  }, payload) {
    roles.deleteRole(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(DELETE_ROLE, payload.roleId);
          commit(SHOW_SUCCESS_MSG, {
            message: '删除系统角色成功。',
            duration: 1000
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  }
}

// mutations
const mutations = {
  [SET_ROLES](state, {
    roles
  }) {
    state.roles = roles
  },
  [UPDATE_ROLE](state, user) {
    //TODO??
  },
  [INSERT_ROLE](state, user) {
    //TODO??
  },
  [DELETE_ROLE](stete, _id) {
    state.roles = state.roles.filter(role => role._id !== _id);
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
